<?php
if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}
define('Adz_alias_fun','1');

function Aurl_charset($str){
	if(CHARSET=='gbk'){
		if(function_exists('mb_convert_encoding')){
			$str = mb_convert_encoding($str,'utf-8',CHARSET);
		}else{
			$str = iconv(CHARSET,'utf-8',$str);
		}
	}
	return $str;
}

//将有别名的帖子自动跳转到别名地址
function autojump(){
	global $_G;
	$aconfig = $_G['cache']['plugin']['alias'];
	if(!empty($_GET['do']) || !empty($_GET['inajax']) || !empty($_GET['goto']) || !empty($_GET['ajaxtarget']) || !empty($_GET['from'])){return;}
	if($_GET['mod']=='viewthread' && $_GET['tid'] && !$_GET['alias'] && $aconfig['autojump']==1){
		$ars = Adz::fetch_con('plugin_alias_bind',array('rid'=>$_GET['tid'],'type'=>1));
		if($ars){
			$alias = Aurl_charset($ars['alias']);
			if($aconfig['urlcode']==1){
				$alias = rawurlencode($alias);
			}
			if($ars['status']==1){
				$url = $_G['siteurl'].str_replace('{alias}',$alias,$aconfig['fm_tid']);
				Header("HTTP/1.1 301 Moved Permanently");
				Header("Location: ".$url);
			}
		}
	}
	if($_GET['mod']=='tag' && $_GET['id'] && !$_GET['alias'] && $aconfig['autojump']==1){
		$ars = Adz::fetch_con('common_tag',array('tagid'=>intval($_GET['id'])));
		if($ars){
			$alias = Aurl_charset($ars['tagname']);
			if($aconfig['urlcode']==1){
				$alias = rawurlencode($alias);
			}
			$url = $_G['siteurl'].str_replace('{tagid}',$alias,$aconfig['tags']);
			Header("HTTP/1.1 301 Moved Permanently");
			Header("Location: ".$url);
		}
	}
}

//伪静态处理
function Arewriteoutput($type, $returntype, $host) {
	global $_G;
	$fextra = '';
	$aconfig = $_G['cache']['plugin']['alias'];
	if($type == 'forum_forumdisplay') {
		list(,,, $fid, $page, $extra) = func_get_args();
		if($_G['setting']['domain']['alist']['subarea'][$fid]){
			$host = "http://".$_G['setting']['domain']['alist']['subarea'][$fid];
		}elseif($_G['setting']['domain']['alist']['forum'][$fid]){
			$host = "http://".$_G['setting']['domain']['alist']['forum'][$fid];
		}else{
			$r = array(
				'{fid}' => empty($_G['setting']['forumkeys'][$fid]) ? $fid : $_G['setting']['forumkeys'][$fid],
				'{page}' => $page ? $page : 1,
			);
		}
	}elseif($type == 'forum_viewthread' || $type == 'forum_viewthread_path') {
		list(,,, $tid, $page, $prevpage, $extra) = func_get_args();
		$r = array(
			'{tid}' => $tid,
			'{page}' => $page ? $page : 1,
			//'{prevpage}' => $prevpage && !IS_ROBOT ? $prevpage : 1,
		);
			$tdata = Adz::fetch_con('forum_thread',array('tid'=>$tid));
			$fid = $tdata['fid'];
			if($type == 'forum_viewthread_path' && $_G['setting']['forumkeys'][$fid]){
				$r['{fid}'] = $_G['setting']['forumkeys'][$fid];
			}else{
				$r['{fid}'] = $fid;
			}
			$rs = Adz::fetch_con('plugin_alias_bind',array('rid'=>$tid,'type'=>1));
			if($rs && $rs['status']==1){
				$alias = $rs['alias'];
				if($aconfig['urlcode']==1){
					$alias = rawurlencode(Aurl_charset($alias));
				}
			}
			file_put_contents(DISCUZ_ROOT.'source/plugin/alias/log.txt',json_encode($r));
		if($alias){$r['{alias}']=$alias;}
	}elseif($type == 'forum_rss'){
		list(,,, $fid, $auth, $extra) = func_get_args();
		$r = array(
			'{fid}' => $fid,
		);
	}elseif($type == 'tags'){
		list(,,, $tagid, $title, $extra) = func_get_args();
		if($title) $extra .= $title;
		$r = array(
			'{tagid}' => $tagid,
		);
		$rs = Adz::fetch_con('common_tag',array('tagid'=>intval($tagid)));
		if($rs){
			$alias = $rs['tagname'];
			if($aconfig['urlcode']==1){
				$alias = rawurlencode(Aurl_charset($alias));
			}
		}
		if($alias){$r['{tagid}']=$alias;}
	}
	if($r['{alias}']){
		if($r['{page}']==1){
			$href = str_replace(array_keys($r), $r, $aconfig['fm_tid']).$fextra;
		}elseif($r['{page}']>1){
			$href = str_replace(array_keys($r), $r, $aconfig['fm_tid_page']).$fextra;
		}
	}elseif($type == 'forum_viewthread_path'){
		if($r['{page}']==1){
			$href = str_replace(array_keys($r), $r,$aconfig['path_tid']).$fextra;
		}elseif($r['{page}']>1){
			$href = str_replace(array_keys($r), $r,$aconfig['path_tid_page']).$fextra;
		}
	}elseif($type == 'forum_forumdisplay'){
		if($r['{page}']>1){
			$href = str_replace(array_keys($r), $r, $aconfig['path_fid_page']).$fextra;
		}elseif($r['{page}']==1){
			$href = str_replace(array_keys($r), $r, $aconfig['path_fid']).$fextra;
		}else{
			$href = '/';
		}
	}elseif($type == 'forum_rss'){
		$href = str_replace(array_keys($r), $r, $aconfig['fm_rss']).$fextra;
	}elseif($type == 'tag'){
		$host = "http://".subdomain('forum').'/';
		$href = $aconfig['tag'];
	}elseif($type == 'tags'){
		if(empty($host)){$host = "http://".subdomain('forum').'/';}
		$href = str_replace(array_keys($r), $r, $aconfig['tags']).$fextra;
	}else{
		$href = str_replace(array_keys($r), $r, $_G['setting']['rewriterule'][$type]).$fextra;
	}
	if(!$returntype) {
		return '<a href="'.$host.$href.'"'.(!empty($extra) ? stripslashes($extra) : '').'>';
	} else {
		return $host.$href;
	}
}
//查询后台设置的应用域名
function subdomain($item){
	global $_G;
	$domain = $_G['setting']['domain'];
	if($domain['app'][$item]){
		$return = $domain['app'][$item];
	}else{
		$return = $domain['app']['default'];
	}
	if(strlen($return)<3){
		$return = $_SERVER['HTTP_HOST'];
	}
	return $return;
}
function Adzcharset($str){
	global $_G;
	if(in_array($_G['charset'],array('gbk','gb2312','GBK','GB2312'))){
		$charsetto = "GBK";
	}elseif(in_array($_G['charset'],array('BIG5','big5'))){
		$charsetto = "BIG5";
	}else{
		$charsetto = false;
	}
	if(function_exists('mb_convert_encoding')){
		if($charsetto) $str = mb_convert_encoding($str,$charsetto,"UTF-8");
	}else{
		if($charsetto) $str = iconv("UTF-8",$charsetto.'//IGNORE',$str);
	}
	return $str;
}
function alias_ping($tid,$type='baidu'){
	global $_G;
	$host = "http://".$_SERVER['HTTP_HOST']."/";
	$rule_fid = $_G['setting']['rewriterule']['forum_forumdisplay'];
	$rule_tid = $_G['setting']['rewriterule']['forum_viewthread'];
	$obj = Adz::fetch_con('forum_thread',array('tid'=>$tid),'tid,fid,subject');
	$aobj = Adz::fetch_con('plugin_alias_bind',array('rid'=>$tid,'type'=>1));
	$furl = $host.str_replace(array('{fid}','{page}'),array($obj['fid'],'1'),$rule_fid);
	if($aobj['alias']){
		loadcache('plugin');
		$rule_tid = $_G['cache']['plugin']['alias']['fm_tid'];
		$turl = $host.str_replace('{alias}',$aobj['alias'],$rule_tid);
	}else{
		$turl = $host.str_replace(array('{tid}','{page}','{prevpage}'),array($obj['tid'],'1','1'),$rule_tid);
	}
	$rss = $host."alias.php?mod=rss&fid=".$obj['fid'];
	if($type=='baidu'){
		return Aping_baidu($obj['subject'],$furl,$turl,$rss);
	}elseif($type=='google'){
		return Aping_google($obj['subject'],$furl,$turl,$rss);
	}
}
function Aping_baidu($title,$index,$url,$rss){
	$xml = '<?xml version="1.0" encoding="UTF-8"?><methodCall>
    <methodName>weblogUpdates.extendedPing</methodName>
    <params>
        <param>
            <value><string>'.$title.'</string></value>
        </param>
        <param>
            <value><string>'.$index.'</string></value>
        </param>
        <param>
            <value><string>'.$url.'</string></value>
        </param>
        <param>
            <value><string>'.$rss.'</string></value>
        </param>
    </params>
</methodCall>';
	$rs = Afun_curl('post',"http://ping.baidu.com/ping/RPC2",$xml,0,array('header'=>array("Content-Type: text/xml;")));
	$obj->rs = preg_match('/>0</',$rs['data']);
	$obj->xml = $xml;
	$obj->note = $rs;
	return $obj;
}
function Aping_google($title,$index,$url,$rss){
	$xml = '<?xml version="1.0" encoding="UTF-8"?><methodCall>
    <methodName>weblogUpdates.extendedPing</methodName>
    <params>
        <param>
            <value><string>'.$title.'</string></value>
        </param>
        <param>
            <value><string>'.$index.'</string></value>
        </param>
        <param>
            <value><string>'.$url.'</string></value>
        </param>
        <param>
            <value><string>'.$rss.'</string></value>
        </param>
    </params>
</methodCall>';
	$rs = Afun_curl('post',"http://blogsearch.google.com/ping/RPC2",$xml,0,array('header'=>array("Content-Type: text/xml;")));
	$obj->rs = preg_match('/>0</',$rs['data']);
	$obj->xml = $xml;
	return $obj;
}

function Afun_curl($type='get',$url,$data,$gzip='1',$arr=array()){
	if($type=='get'){
		echo $url .= Afun_urlstr($data);
	}
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	if($arr['header']) curl_setopt($curl, CURLOPT_HTTPHEADER, $arr['header']);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
	if($gzip=='1'){
		curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
	}
	if($type=='post'){
		$post_data = Afun_urlstr($data);
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
	}
	$file_contents = curl_redir_exec($curl);
	curl_close($curl);
	list($obj['header'], $obj['data']) = explode("\r\n\r\n", $file_contents, 2);
	return $obj;
}
function Afun_urlstr ($data,$parent=''){
	$str='';$add='';
	if(is_object($data) || is_array($data)){
		foreach ($data as $k=>$v){
			$add=$k;
			if($parent || (strlen($parent)==1 && $parent==0)){$add = $parent."[".$k."]";}
			if(is_object($data) || is_array($data)){
				$str .= Afun_urlstr($v,$add);
			}else{
				$str .= "&".$add."=".$v;
			}
		};
	}else{if($parent || (strlen($parent)==1 && $parent==0)){$str = "&".$parent."=".$data;}else{$str = "&".$data;}}
	return $str;
}
function curl_redir_exec($ch,$debug=""){
	static $curl_loops = 0;
	static $curl_max_loops = 20;
	if ($curl_loops++ >= $curl_max_loops){
		$curl_loops = 0;
		return FALSE;
	}
	curl_setopt($ch, CURLOPT_HEADER, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$data = curl_exec($ch);
	
	$debbbb = $data;
	list($header, $data) = explode("\n\n", $data, 2);
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	if ($http_code == 301 || $http_code == 302){
		$matches = array();
		preg_match('/Location:(.*?)\n/', $header, $matches);
		$url = @parse_url(trim(array_pop($matches)));
		if (!$url){
			$curl_loops = 0;
			return $data;
		}
		$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
		$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
		curl_setopt($ch, CURLOPT_URL, $new_url);
		return curl_redir_exec($ch);
	} else {
		$curl_loops=0;
		return $debbbb;
	}
}
?>